/**
 * CommentsServices
 */
const CommentModel = require('../models/CommentModel')
const NewsModel = require("../models/NewsModel");
const CommentsServices = {
    add: async data => {
        return CommentModel.create(data)
    },
    deleteOne: async comment_id => {
        if(!comment_id) {
            return Promise.reject('id未传，删除失败')
        }
        if(!await CommentModel.findOne({ comment_id })) {
            return Promise.reject('删除的数据不存在')
        }
        return CommentModel.deleteOne({ comment_id })
    },
    shield: async (comment_id, comment_status) => {
        if(!comment_id) {
            return Promise.reject('id未传，删除失败')
        }
        if(!await CommentModel.findOne({ comment_id })) {
            return Promise.reject('屏蔽的数据不存在')
        }
        return CommentModel.updateOne({ comment_id }, {comment_status})
    },
    query: async ({ comment_content,comment_news_id,comment_status, page,limit }) => {
        let queryData = {}
        if(comment_news_id) {
            queryData = {
                comment_news_id
            }
        }
        if(comment_status) queryData.comment_status = comment_status
        const pattern = new RegExp(`.*${comment_content}.*`, 'i');
        return CommentModel.find(comment_content ?  { comment_content: { $regex: pattern }, ...queryData } :{...queryData}).skip((page - 1) * limit).limit(limit)
    },
    queryCount: async ({ comment_content }) => {
        const pattern = new RegExp(`.*${comment_content}.*`, 'i');
        return CommentModel.countDocuments(comment_content ?  { comment_content: { $regex: pattern } } :{})
    }
}

module.exports = CommentsServices
